import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useMenuStore } from '@/stores/menu'

// 基础路由配置
const baseRoutes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/test/route',
    name: 'RouteTest',
    component: () => import('@/views/test/RouteTest.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    meta: { requiresAuth: true },
    redirect: '/admin/dashboard',
    children: [
      // 只保留一个默认的dashboard路由，其他路由将动态添加
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: {
          requiresAuth: true,
          title: '仪表板',
          icon: 'Dashboard'
        }
      }
    ]
  }
]

// 组件映射表 - 将路径映射到对应的组件
const componentMap = {
  '/dashboard': () => import('@/views/admin/Dashboard.vue'),
  '/system/user': () => import('@/views/admin/system/UserManagement.vue'),
  '/system/role': () => import('@/views/admin/system/RoleManagement.vue'),
  '/system/permission': () => import('@/views/admin/system/PermissionManagement.vue'),
  '/system/group': () => import('@/views/admin/system/GroupManagement.vue'),
  '/profile': () => import('@/views/admin/Profile.vue'),
  '/settings': () => import('@/views/admin/Settings.vue'),
  '/test/user-update': () => import('@/views/test/UserUpdateTest.vue'),
  '/test/profile': () => import('@/views/test/ProfileTest.vue'),
  // 可以继续添加更多组件映射
}

// 根据菜单数据生成路由
const generateRoutesFromMenu = (menuTree) => {
  const routes = []

  const processMenuItem = (menuItem) => {
    // 只处理菜单类型且有路径的项目
    if (menuItem.type === 1 && menuItem.path && menuItem.isLeaf) {
      const component = componentMap[menuItem.path]
      if (component) {
        // 直接使用菜单路径，去掉开头的 /
        const routePath = menuItem.path.startsWith('/') ? menuItem.path.substring(1) : menuItem.path

        routes.push({
          path: routePath,
          name: menuItem.code,
          component,
          meta: {
            title: menuItem.name,
            icon: menuItem.icon,
            code: menuItem.code,
            permissions: [menuItem.code]
          }
        })
      }
    }

    // 递归处理子菜单
    if (menuItem.children && menuItem.children.length > 0) {
      menuItem.children.forEach(processMenuItem)
    }
  }

  menuTree.forEach(processMenuItem)
  return routes
}

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: baseRoutes
})

// 动态添加路由的函数
export const addDynamicRoutes = (menuTree) => {
  const dynamicRoutes = generateRoutesFromMenu(menuTree)

  // 添加新的动态路由
  dynamicRoutes.forEach(route => {
    router.addRoute('Admin', route)
  })

  console.log('动态路由已添加:', dynamicRoutes)
}

// 重置动态路由状态的函数
export const resetDynamicRoutes = () => {
  dynamicRoutesAdded = false
  console.log('动态路由状态已重置')
}

// 标记是否已经添加过动态路由
let dynamicRoutesAdded = false

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('=== 路由守卫开始 ===')
  console.log('访问路径:', to.path)
  console.log('来源路径:', from.path)
  console.log('路由元信息:', to.meta)
  console.log('动态路由已添加:', dynamicRoutesAdded)

  // 对于不需要认证的路由，直接通过
  if (!to.meta.requiresAuth) {
    console.log('路由不需要认证，直接通过')
    next()
    return
  }

  try {
    const userStore = useUserStore()
    const menuStore = useMenuStore()

    console.log('用户登录状态:', userStore.isLoggedIn)
    console.log('菜单数量:', menuStore.menuTree.length)

    // 如果访问需要认证的页面但用户未登录
    if (!userStore.isLoggedIn) {
      console.log('需要认证但未登录，跳转到登录页')
      next('/login')
      return
    }

    // 如果用户已登录但菜单未加载或动态路由未添加，先加载菜单和动态路由
    if (menuStore.menuTree.length === 0 || !dynamicRoutesAdded) {
      console.log('用户已登录但菜单未加载或动态路由未添加，开始加载菜单')
      try {
        const menuResult = await menuStore.getCurrentUserMenu()
        if (menuResult && menuResult.success) {
          addDynamicRoutes(menuStore.menuTree)
          dynamicRoutesAdded = true
          console.log('菜单和动态路由加载完成')

          // 如果当前访问的路径不是dashboard，需要重新导航以确保动态路由生效
          if (to.path !== '/admin/dashboard' && to.path.startsWith('/admin/')) {
            console.log('重新导航到:', to.path)
            next({ ...to, replace: true })
            return
          }
        } else {
          console.error('菜单加载失败:', menuResult?.message || '未知错误')
          await userStore.logout()
          dynamicRoutesAdded = false
          next('/login')
          return
        }
      } catch (error) {
        console.error('加载菜单时发生异常:', error)
        await userStore.logout()
        dynamicRoutesAdded = false
        next('/login')
        return
      }
    }

    console.log('路由守卫通过，继续导航到:', to.path)
    next()
  } catch (error) {
    console.error('路由守卫执行出错:', error)
    console.log('出错后跳转到登录页')
    next('/login')
  }

  console.log('=== 路由守卫结束 ===')
})

export default router